/*
 * Copyright (C) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "video_sample_base.h"
#include <chrono>
#include "av_codec_sample_log.h"
#include "av_codec_sample_error.h"

#undef LOG_TAG
#define LOG_TAG "Base"

namespace {
    using namespace std::string_literals;
    using namespace std::chrono_literals;
} // namespace


VideoSampleBase::~VideoSampleBase() {
    StartRelease();
}

int32_t VideoSampleBase::WaitForDone() {
    AVCODEC_SAMPLE_LOGI("Wait called");
    std::unique_lock<std::mutex> lock(mutex_);
    doneCond_.wait(lock);
    if (releaseThread_ && releaseThread_->joinable()) {
        releaseThread_->join();
        releaseThread_.reset();
    }
    AVCODEC_SAMPLE_LOGI("Done");
    return AVCODEC_SAMPLE_ERR_OK;
}

void VideoSampleBase::Release() {}

void VideoSampleBase::StartRelease() {
    if (releaseThread_ == nullptr) {
        AVCODEC_SAMPLE_LOGI("Start to release");
        releaseThread_ = std::make_unique<std::thread>(&VideoSampleBase::Release, this);
    }
}

void VideoSampleBase::ThreadSleep() {
    if (sampleInfo_.frameInterval <= 0) {
        return;
    }

    thread_local auto lastPushTime = std::chrono::system_clock::now();
    auto beforeSleepTime = std::chrono::system_clock::now();
    std::this_thread::sleep_until(lastPushTime + std::chrono::milliseconds(sampleInfo_.frameInterval));
    lastPushTime = std::chrono::system_clock::now();

    AVCODEC_SAMPLE_LOGW("Sleep time: %{public}2.2fms",
                        static_cast<std::chrono::duration<double, std::milli>>(lastPushTime - beforeSleepTime).count());
}
